import axios from '@/core/utils/AxiosRequest'
// {url: '', status:'pending / done', returnData: null, time: 0 }
const reqList= []
// 节流请求
function ThrottleRequest(url, param){
  return new Promise((resolve, reject)=>{
    const req = reqList.find(item=> item.url == url +JSON.stringify(param))
    //有效期判断
    if(req) {
      if(req.status == 'pending'){
        let timer =setInterval(()=>{
          if(req.status == 'done'){
            //console.info('等到结果可以返回了有。。。。done')  
            clearInterval(timer)
            resolve(req.returnData)
          }else if(req.status == 'error'){
            clearInterval(timer)
            reject(req.returnData)
          }
        }, 200)
      }else {
        resolve(req.returnData)
      }
    }else{
      //不存在的话
      let reqNew ={url: url+JSON.stringify(param), status: 'pending', returnData: null}
      reqList.push(reqNew)
      axios.get(url, { params: param }).then(data=>{
        reqNew.returnData = data
        reqNew.status = 'done'
        reqNew.time = new Date().getTime()
        resolve(data)
      }).catch(err=>{
        reqNew.returnData = err
        reqNew.status = 'error'
        reject(err)
      }).finally(()=>{
        setTimeout(()=>{
          //console.log('我要清空了之前反回的结果', url, JSON.stringify(param))
          let idx = reqList.findIndex(item=> item.url == url+JSON.stringify(param))
          reqList.splice(idx, 1)
          //console.log(reqList)
        }, 2000)
      })
    }
  })
}
export default ThrottleRequest